package dao

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strings"
	"view-crawler-backend/internal/dao/entity"
)

func AddTaskExecRecord(db *gorm.DB, taskExecRecord *entity.TaskExecRecord) error {
	return db.Table("task_exec").Create(taskExecRecord).Error
}

func QueryTaskExecRecordCount(db *gorm.DB, taskId int64) (int64, error) {
	var num int64
	if err := db.Table("task_exec").Where("task_id=?", taskId).Count(&num).Error; err != nil {
		return 0, err
	}
	return num, nil
}

// DeleteOldestTaskExecRecord 删除某个任务最早一次的执行记录,并返回其execId
func DeleteOldestTaskExecRecord(db *gorm.DB, taskId int64) (int, error) {
	var taskExecRecordList []entity.TaskExecRecord
	if err := db.Table("task_exec").Clauses(clause.Returning{Columns: []clause.Column{{Name: "exec_id"}}}).
		Where("id = (?)",
			db.Table("task_exec").Select("id").Where("task_id = ?", taskId).Order("exec_id").Limit(1)).
		Delete(&taskExecRecordList).Error; err != nil {
		return 0, err
	}
	return taskExecRecordList[0].ExecId, nil
}

// DeleteExecData 删除某个任务某一次执行所采集的所有数据
func DeleteExecData(db *gorm.DB, taskId int64, execId int) error {
	return db.Table(fmt.Sprintf("t%d", taskId)).Where("execId = ?", execId).Delete(nil).Error
}

func CreateExecDataTable(db *gorm.DB, taskId int64, fieldList []string) error {
	for i := 0; i < len(fieldList); i++ {
		fieldList[i] = fieldList[i] + " TEXT"
	}
	sql := fmt.Sprintf("CREATE TABLE IF NOT EXISTS t%d (%s,execId INTEGER);", taskId, strings.Join(fieldList, ","))
	return db.Exec(sql).Error
}

func DeleteExecDataTable(db *gorm.DB, taskId int64) error {
	return db.Migrator().DropTable(fmt.Sprintf("t%d", taskId))
}

// BatchAddExecData 批量插入采集到的数据
func BatchAddExecData(db *gorm.DB, taskId int64, dataList []map[string]any) error {
	return db.Table(fmt.Sprintf("t%d", taskId)).Create(&dataList).Error
}
